<?php

namespace oneStep\routes;

class Router
{
    /** 路由
     * @param string $path
     * @param $params
     */
    public static $data = [];
    public static $gropData = [];
    public static $middleware = [];
    public static $path;

    public static function routerHand()
    {
        $uri    = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $uri    = preg_replace('/\/index.php/', '', $uri);
        $method = $_SERVER['REQUEST_METHOD'];

        if (!isset(self::$data[$uri])) {
            throw new \Exception('rotuer not existent',404);
        }

        $current = self::$data[$uri];
        if ($current['method'] != 'ANY') {
            if ($method != $current['method']) {
                throw new \Exception($current['method'] . ' not existent');
            }
        }
        if (!is_array($current['params'])) {
            $current['params']();
            exit();
        }
        //中间件处理
        if (isset($current['middleware'])) {
            return (new  $current['middleware'])->handle(
                function () use ($current) {
                    return self::reflect($current);
                }
            );
        }
        return self::reflect($current);
    }

    /**
     * @param $current
     * @return mixed
     * @throws \ReflectionException
     */
    public static function reflect($current)
    {
        $method = new \ReflectionMethod($current['params'][0], $current['params'][1]);
        $args   = [];
        foreach ($method->getParameters() as $parameter) {
            if ($class = $parameter->getClass()) {
                $args[] = new $class->name;
            }
        }
        return $method->invokeArgs(new $current['params'][0], $args);
    }

    /**
     * @param string $path
     * @param $params
     */
    public static function get(string $path, $params)
    {
        self::set($path, $params, 'GET');
        return new  Router();
    }

    /**
     * @param string $path
     * @param $params
     */
    public static function post(string $path, $params)
    {
        self::set($path, $params, 'POST');
        return new  Router();
    }


    /**
     * @param $path
     * @param $params
     * @param $method
     */
    public static function any(string $path, $params)
    {
        self::set($path, $params, 'ANY');
        return new  Router();
    }

    /**
     * @param $path
     * @param $params
     * @param $method
     */
    public static function set($path, $params, $method)
    {
        self::$data[$path]['method']     = $method;
        self::$data[$path]['routerPath'] = $path;
        self::$data[$path]['params']     = $params;
        self::$path                      = $path;
    }


    /**
     * 调用中间件
     * @param string $middlewareName
     */
    public function middleware(string $middleware)
    {
        self::$data[self::$path]['middleware'] = $middleware;
    }
}